home *** CD-ROM | disk | FTP | other *** search
- Path: engnews2.Eng.Sun.COM!usenet
- From: nitin@more.eng.sun.com (Nitin More [CONTRACTOR])
- Newsgroups: comp.lang.c++
- Subject: Re: Quick, easy question on externs...
- Date: 11 Jan 1996 20:30:59 GMT
- Organization: SunSoft
- Message-ID: <NITIN.96Jan11123059@more.eng.sun.com>
- References: <30F4333C.41A9@omni.voicenet.com> <30f46f5b.430017088@nntp.ix.netcom.com>
- NNTP-Posting-Host: more.eng.sun.com
- In-reply-to: miker3@ix.netcom.com's message of Thu, 11 Jan 1996 02:19:23 GMT
-
- In article <30f46f5b.430017088@nntp.ix.netcom.com> miker3@ix.netcom.com (Mike Rubenstein) writes:
-
- > From: miker3@ix.netcom.com (Mike Rubenstein)
- > Newsgroups: comp.lang.c++
- > Date: Thu, 11 Jan 1996 02:19:23 GMT
- > Organization: Netcom
- > X-NETCOM-Date: Wed Jan 10 6:18:00 PM PST 1996
- >
- > David Zuckman <dzuckman@omni.voicenet.com> wrote:
- >
- > |>I got two source files:
- > |>
- > |>z1.cpp
- > |>======
- > |> #include <iostream.h>
- > |>
- > |> extern int const x;
- > |>
- > |> void main( void ) {
- > |> x;
- > |> }
- > |>
- > |>z2.cpp
- > |>======
- > |> int const x = 5;
- > |>
- > |>They compile and link fine (I'm using MS Visual C++ 2.1).
- > |>
- > |>I change the line in z1.cpp that reads
- > |> x;
- > |>to
- > |> cout << x;
- > |>and I get
- > |>
- > |> Incrementally linking...
- > |> LINK : performing full link
- > |> z1.obj : error LNK2001: unresolved external symbol "?x@@3HB
- > (int const x)"
- > |> WinDebug/dbx.exe : error LNK1120: 1 unresolved externals
- > |>
- > |>What gives?
- >
- > Looks like the optimizer allowed you to get away with incorrect code
- > initially. What probably happend is that the compiler realized that
- > x; doesn't do anything useful and eliminated the statement so there
- > was no reference to x in the object module for z1.cpp.
- >
- > In C++, const implies static linkage so the x defined in z2.cpp is not
- > available outside that file. To fix this, change the definition in
- > z2.cpp to
- >
- > extern int const x = 5;
- >
- >
- > Michael M Rubenstein
- >
-
- Michael is right but even better way to do this is to put the extern
- definition in a header file and include it in both the files so that
- inconsistencies in the value of x is immediately noticed at compile
- time. You still have to assign the value to x in z2.cpp. Now if
- you change the value of x in one place and forgot to change it in
- the other, the compiler will immediately warn you.
-
- -Nitin
-
- --
- ----------------------------------------------------------------------
- Nitin More
- SunSoft, Bldg 16 Off: (415) 786 7109
- Menlo Park, CA Fax: (415) 786 7957 e-mail: nitin@more.eng.sun.com
- ----------------------------------------------------------------------
-